﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Text.RegularExpressions;
using ueEngine.Web.WebLogic.Model;
using ueEngine.Biz.Core.AppService.Member;
using ueEngine.Web.WebLogic;
using ueEngine.Framework.Common;
using ueEngine.Biz.Inf.LogicEntity;
using ueEngine.Framework.Exception;

namespace ueEngine.Web.Controllers
{
    //[TraceBehavior]
    [ErrorHandle]
    [Compress]
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Login()
        {
            return View(new LoginVModel());
        }
        /// <summary>
        /// 验证用户名是否已经存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns>存在返回1；不存在返回0</returns>
        public int UsernameValid(string username)
        {
            return new UserService(username).CheckUserName();
        }
        [HttpPost]
        public ActionResult Login(LoginVModel model)
        {
            if (String.IsNullOrEmpty(model.UserName) ||
                String.IsNullOrEmpty(model.Password) ||
                String.IsNullOrEmpty(model.Validator))
            {
                model.Pass = false;
                model.FaildMessage = "您的输入有误，请查证";
                return View(model);
            }
            if (ValidateValidateCode(model.Validator))
            {
                var user = new UserService(model.UserName).Login(model.Password);
                if (user == null)
                {
                    model.Pass = false;
                    model.FaildMessage = "用户名或密码错误，请重新输入";
                    return View(model);
                }
                else
                {
                    if (user.IsActivate)
                    {
                        if (String.Equals(model.Remember, "on"))
                        {
                            System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserName, true);
                        }
                        else
                        {
                            System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserName, false);
                        }
                        string preurl = Request.Params["ReturnUrl"];
                        if (String.IsNullOrEmpty(preurl))
                        {
                            return Redirect("/Home/Index");
                        }
                        else
                        {
                            return Redirect(System.Web.HttpContext.Current.Server.UrlDecode(preurl));
                        }
                    }
                    else
                    {
                        ViewData["AlterActivate"] = "1";
                        ViewData["username"] = model.UserName;
                        model.Pass = true;
                        model.FaildMessage = "";
                        return View(model);
                    }
                }
            }
            else
            {
                model.Pass = false;
                model.FaildMessage = "验证码输入有误";
            }
            return View(model);
        }
        public ActionResult LogOut()
        {
            string ref_uri = HttpContext.GetParameter("ref_uri");
            System.Web.Security.FormsAuthentication.SignOut();
            if (String.IsNullOrEmpty(ref_uri))
            {
                return Redirect("/Home/Index");
            }
            else
            {
                return Redirect(ref_uri);
            }
        }
        public ActionResult CRegister()
        {
            return View(new CRegisterVModel());
        }
        [HttpPost]
        public ActionResult CRegister(CRegisterVModel model)
        {
            if (String.IsNullOrEmpty(model.UserName) ||
                !new Regex("\\w+@\\w+\\.\\w+").IsMatch(model.UserName) ||
               String.IsNullOrEmpty(model.Password) ||
                model.Password != model.Confirm)
            {
                model.Pass = false;
                model.FaildMessage = "您的输入有误，请查证";
                return View(model);
            }
            if (!ValidateValidateCode(model.Validator))
            {
                model.Pass = false;
                model.FaildMessage = "验证码输入错误，请重新输入";
                return View(model);
            }
            var result = new SeekerService(model.UserName).Register(model.Password, model.Confirm, model.Location, model.Collage);
            if (result == null)
            {
                model.Pass = false;
                model.FaildMessage = "用户名已存在，请更改用户名";
                return View(model);
            }
            else 
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Trace, String.Format("用户注册会员完成，userName:{0},password:{1},confirm:{2}"
                    , model.UserName, model.Password, model.Confirm));
            }
            return Redirect("/Account/RegisterDone");
        }

        public ActionResult BRegister()
        {
            return View(new BRegisterVModel());
        }
        [HttpPost]
        public ActionResult BRegister(BRegisterVModel model)
        {
            model.Email = model.UserName;
            if (String.IsNullOrEmpty(model.UserName) ||
                !new Regex("\\w+@\\w+\\.\\w+").IsMatch(model.UserName) ||
                String.IsNullOrEmpty(model.Email) ||
                !new Regex("\\w+@\\w+\\.\\w+").IsMatch(model.Email) ||
                String.IsNullOrEmpty(model.CompanyName) ||
                String.IsNullOrEmpty(model.Location) ||
                String.IsNullOrEmpty(model.Phone) ||
               String.IsNullOrEmpty(model.Password) ||
                model.Password != model.Confirm)
            {
                model.Pass = false;
                model.FaildMessage = "您的输入有误，请查证";
                return View(model);
            }
            if (!ValidateValidateCode(model.Validator))
            {
                model.Pass = false;
                model.FaildMessage = "验证码输入错误，请重新输入";
                return View(model);
            }
            var item = new FirmService(model.UserName).Register(
                new MemberModel()
                {
                    CorporationInfo=new CorporationModel(){
                        CompanyName = model.CompanyName,
                        EMail = model.Email,
                        Location = model.Location,
                        Phone = model.Phone
                    },
                    Password = model.Password,
                    Location = model.Location,
                    Phone = model.Phone,
                    QQ = model.QQ
                });
            if (item == null)
            {
                model.Pass = false;
                model.FaildMessage = "用户名已存在，请更改用户名";
                return View(model);
            }
            else
            {
                LogHelper.Write( CommonLogger.UserSystem, LogLevel.Trace, String.Format("用户注册商家完成，userName:{0},password:{1},confirm:{2}"
                        , model.UserName, model.Password, model.Confirm));
            }
            return Redirect("/Account/RegisterDone");
        }

        /// <summary>
        /// 服务条款
        /// </summary>
        /// <returns></returns>
        public ActionResult Agreement()
        {
            return View();
        }
        /// <summary>
        /// 注册完成，请去邮箱激活
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterDone()
        {
            return View();
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="t"></param>
        [HttpGet]
        public void ValidateToken()
        {
            string t = HttpContext.GetParameter("t");
            const int width = 60, height = 25;

            Bitmap aBmp = new Bitmap(width, height);
            Graphics aGrph = Graphics.FromImage(aBmp);
            aGrph.FillRectangle(new SolidBrush(Color.FromArgb(68, 68, 68)), 0, 0, width, height);//255,153,0

            //string adPitch = ssolib.Cryptogram.CommonDecrypt(Request.QueryString["yymm"].ToString());

            //为了解决浏览器后退，验证码不刷新的问题，对验证码的实现做了修改。 By Zhenli W.  2004-03-21
            string adPitch = Cryptogram.CommonEncrypt(t);

            adPitch = adPitch.Replace("/", "");
            adPitch = adPitch.Replace("+", "");
            adPitch = adPitch.Replace("=", "");

            adPitch = adPitch.Substring(0, 4);
            /*if(adPitch.Length < 4)
            {
                for(int i=0;i<4-adPitch.Length;i++)
                {
                    adPitch = adPitch + (new Random(i)).Next(0,9).ToString();
                }
            }*/
            //End Updated by Zhenli W.

            adPitch = adPitch.ToUpper();

            //过虑0为O,I和1
            adPitch = adPitch.Replace("0", "O");
            adPitch = adPitch.Replace("1", "I");
            new VerifyCodeImage().CreateImageOnPage(adPitch, 3, System.Web.HttpContext.Current);
        
        }
        /// <summary>
        /// 验证验证码是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateValidateCode(string code)
        {
            bool result;

            string token = Request.Params["token"];
            if (token == null)
            {
                result = false;
            }
            else
            {
                token = Cryptogram.CommonEncrypt(token);
                //过虑加密后出现的非法字符
                token = token.Replace("/", "");
                token = token.Replace("+", "");
                token = token.Replace("=", "");
                token = token.Substring(0, 4).ToString();
                token = token.ToLower();
                //过虑0为O,I和1
                token = token.Replace("0", "o");
                token = token.Replace("1", "i");
                string validStr = code.ToLower();
                //o,0转换，i,1转换
                validStr = validStr.Replace("0", "o");
                validStr = validStr.Replace("1", "i");
                if (validStr != token)
                    result = false;
                else
                    result = true;
            }
            return result;
        }

        public ActionResult Activation()
        {
            string token = HttpContext.GetParameter("token");
            string userName = string.Empty;
            if (new UserService(string.Empty).ValidToken(token,ref userName,0))
            {
                var userEntity = new UserService(userName).Activation();
                //如果激活成功
                if (userEntity != null)
                {
                    System.Web.Security.FormsAuthentication.SetAuthCookie(userName,false);
                    //如果该代理人维护了商家信息。则本代理人是商家代理人
                    if (userEntity.Role == MemberStatus.Firm)
                    {
                        //商家代理人
                        ViewData["agentType"] = "00";
                    }
                    else
                    {
                        //个人用户
                        ViewData["agentType"] = "01";
                    }
                    return View();
                }
                else
                {
                    return Redirect("/Account/ActivationFail?type=1&usn=" + userName);
                }
            }
            else
            {
                //验证token失败
                return Redirect("/Account/ActivationFail?type=0&usn=" + userName);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">0：验证token失败 1：激活失败，请重试</param>
        /// <returns></returns>
        public ActionResult ActivationFail(string type, string usn)
        {
            return View();
        }

        public int ReSendEmail(string username)
        {
            return new UserService(username).ReSendEmail();
        }

        public ActionResult ResetPassword()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ResetPassword(string UserName)
        {
            try
            {
                if (!String.IsNullOrEmpty(UserName))
                {
                    var user = new UserService(UserName);
                    if (user.GetUser() != null)
                    {
                        user.MailForResetPassword();
                        return Redirect("/account/goverify");
                    }
                }
                ViewData["faild"] = 1;
                return View();

            }
            catch (ContextException e)
            {
                if (e.ExceptionType == ExceptionType.OutOfDataBase)
                {
                    ViewData["faild"] = "1";
                    return View();
                }
                throw e;
            }
        }
        public ActionResult GoVerify()
        {
            return View();
        }
        public ActionResult VerifyUser()
        {
            string u = HttpContext.GetParameter("u");
            string token = HttpContext.GetParameter("token").Trim();
            string UserName = EncodeByBase64.Decode(u);
            token = EncodeByBase64.Decode(token);
            if (!String.IsNullOrEmpty(UserName) && !String.IsNullOrEmpty(token))
            {
                try
                {
                    var o = new UserService(UserName);
                    if (o.VerifyResetPasswordToken(token) != null)
                    {
                        ViewData["username"] = u;
                        return View();
                    }
                }
                catch (ContextException) { }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.Zone, e);
                }
            }
            return Redirect("/account/verifyfail");
        }
        public ActionResult verifyfail()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ResetPasswordDone(string UserName, string Password, string Confirm)
        {
            UserName = EncodeByBase64.Decode(UserName);
            if (Password == Confirm)
            {
                new UserService(UserName).ChangePassword(Password);
            }
            return View();
        }
    }
}
